<!--
 * @Author: liaoxing
 * @Date: 2021-12-16 09:16:15
 * @LastEditors: liaoxing
 * @LastEditTime: 2022-03-04 13:59:17
 * @Description: liaoxing created
 * @FilePath: \pin-xin-admin\src\views\business\financial\index.vue
-->
<template>
  <div class="financial">
    <div class="radioBox flex-align-center">
      <el-radio-group v-model="factory">
      <el-radio-button :label="''">全部</el-radio-button>
      <el-radio-button :label="'龙华工厂'">龙华工厂</el-radio-button>
      <el-radio-button :label="'盐田新工厂'">盐田新工厂</el-radio-button>
      <el-radio-button :label="'盐田工厂'">盐田工厂</el-radio-button>
      </el-radio-group>
    </div>
    <datePicker @queryFinanceReport="queryFinanceReportCenter"></datePicker>
    <div class="financialTableBox">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        row-key="id"
        lazy
        :load="loadChildren"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column
          prop="project"
          label="标签"
          :width="keyList && keyList.length < 9 ? '' : 200"
          fixed>
        </el-table-column>
        <el-table-column label="时间" v-if="keyList">
          <el-table-column
            v-for="(item, index) in keyList"
            :key="'keyList' + index"
            :prop="item"
            :label="item"
            width="160">
            <template slot-scope="scope">
              <span :class="{'color-red': scope.row[item] < 0}">
                {{ scope.row[item] }}
                <span class="finger badgeIconBox" v-if="scope.row.tips && scope.row.tips[item]" @click="openAbnormalData(item, scope.row.tips[item])">
                  <el-badge class="mark" :value="scope.row.tips[item].length" />
                </span>
              </span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column
          label="合计"
          fixed="right"
          :width="keyList && keyList.length < 9 ? '' : 160">
          <template slot-scope="scope">
            <span :class="{'color-red': (getSum(scope.row) * 1).toFixed(2) < 0}">{{ (getSum(scope.row) * 1).toFixed(2) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer
      :title="currentAbnormalDate + '异常数据'"
      :visible.sync="abnormalDrawer"
      :size="'50%'"
      direction="rtl">
                <!-- :span-method="objectSpanMethod" -->
      <div style="padding: 16px">
        <el-table
          :data="currentAbnormalData"
          border
          stripe
          height="850"
          :span-method="objectSpanMethod"
          style="width: 100%">
          <el-table-column
            prop="project"
            label="项目"
            width="100">
          </el-table-column>
          <el-table-column
            prop="model"
            label="机型">
          </el-table-column>
          <el-table-column
            prop="materialName"
            label="材料名称">
          </el-table-column>
          <el-table-column
            prop="price"
            label="价格"
            width="80">
          </el-table-column>
          <el-table-column
            prop="entryNo"
            label="入库单号"
            width="150">
          </el-table-column>
          <el-table-column
            prop="qty"
            label="数量"
            width="80">
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import datePicker from '@/components/datePicker/datePicker'
import timeTrans from '@/utils/timeTrans'
export default {
  name: "financial",
  components: {
    datePicker
  },
  data () {
    return {
      initRange: {
        start: timeTrans.getYMD(new Date(new Date().getFullYear() + '/' + (new Date().getMonth() + 1) + '/1')),
        field: 'date',
        end: timeTrans.getYMD(new Date(new Date().getTime() - 24 * 60 * 60 * 1000))
      },
      tableData: [],
      keyList: null,
      currentRange: null,
      loading: false,
      factory: "",
      abnormalDrawer: false,
      currentAbnormalDate: null,
      currentAbnormalData: null,
      tableGroupIndex: {}
    }
  },
  watch: {
    factory (val) {
      if (this.currentRange.pid) {
        delete this.currentRange.pid
      }
      this.queryFinanceReport(this.currentRange, val)
    }
  },
  created () {
    if (this.initRange.start > this.initRange.end) {
      this.initRange.end = this.initRange.start
    }
    this.queryFinanceReport(this.initRange, this.factory)
  },
  methods: {
    queryFinanceReportCenter (params) {
      this.queryFinanceReport(params, this.factory)
    },
    queryFinanceReport (params, factory) {
      if (!params) {
        params = this.initRange
      }
      params.tenantId = factory
      this.currentRange = JSON.parse(JSON.stringify(params))
      this.loading = true
      this.$report.queryFinanceReport(params)
        .then(res => {
          if (res.code === 200) {
            this.createTableData(res.data)
            this.loading = false
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    createTableData (data) {
      this.keyList = data.column
      this.$nextTick(() => {
        this.tableData = data.data
      })
      // this.tableData = data.data
    },
    /* 打开异常数据抽屉 */
    openAbnormalData (title, data) {
      this.abnormalDrawer = true
      this.tableGroupIndex = {}
      this.currentAbnormalDate = title
      this.currentAbnormalData = this.classifyList(data, 'project', 'model')
    },
    /* 数组归类 */
    classifyList (list, key, key2) {
      let classifyObj = {}
      /* 根据名称归类 */
      list.forEach(item => {
        let newKey = item[key].replace(' ', '')
        if (!classifyObj[newKey]) {
          classifyObj[newKey] = []
          classifyObj[newKey].push(item)
        } else {
          classifyObj[newKey].push(item)
        }
      })   
      /* 合并，并给出每个数组在其中的终点下标 */
      let temp = []
      let res = []
      for (let i in classifyObj) {
        temp.push(classifyObj[i].length)
        if (key2) {
          classifyObj[i] = this.classifyList(classifyObj[i], key2)
        }
        res = res.concat(classifyObj[i])
      }
      
      if (!this.tableGroupIndex[key]) {
        this.tableGroupIndex[key] = []
      }
      
      let length = this.tableGroupIndex[key].length
      let max = this.tableGroupIndex[key].length ? this.tableGroupIndex[key][length - 1] : 0

      temp.forEach((it, ind) => {
        if (!ind && !length) {
          this.tableGroupIndex[key].push(it)
        } else {
          this.tableGroupIndex[key].push(this.getIndexSum(temp, ind, max))
        }
      })
      return res
    },
    getIndexSum (list, index, length) {
      let num = length
      for(let i = 0 ; i < index + 1; i++) {
        num += list[i]
      }
      return num
    },
    getSum (list) {
      let newList = JSON.parse(JSON.stringify(list))
      delete newList.hasChildren
      delete newList.id
      delete newList.project
      delete newList.tips
      const keys = Object.keys(newList)
      let num = 0
      keys.forEach(item => {
        if ((typeof newList[item] == 'string') && newList[item].constructor == String ) {
          return num = ''
        }
        num = this.addFloatNum(newList[item], num)
      })
      return num
    },
    addFloatNum (num1, num2) {
      var sq1,sq2,m;
      try {
        sq1 = num1.toString().split(".")[1].length
      }
      catch (e) {
        sq1 = 0
      }
      try {
        sq2 = num2.toString().split(".")[1].length
      }
      catch (e) {
        sq2 = 0
      }
      m = Math.pow(10,Math.max(sq1, sq2))
      return (num1 * m + num2 * m) / m
    },
    loadChildren (tree, treeNode, resolve) {
      this.currentRange.pid = tree.id
      this.loading = true
      this.$report.queryFinanceReport(this.currentRange)
        .then(res => {
          if (res.code === 200) {
            resolve(res.data.data)
            this.loading = false
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return this.getRowCol(rowIndex, 'project')
      }

      if (columnIndex === 1) {
        return this.getRowCol(rowIndex, 'model')
      }
    },
    getRowCol (rowIndex, key) {
      for (let i = 0; i < this.tableGroupIndex[key].length; i++) {
        let item = this.tableGroupIndex[key][i]

        if (i == 0) {
          if (rowIndex < item) {
            if (rowIndex == 0) {
              return {
                rowspan: item,
                colspan: 1
              }
            } else {
              return {
                rowspan: 0,
                colspan: 0
              }
            }
          }
        } else {
          let beforeItem  = this.tableGroupIndex[key][i - 1]
          if (rowIndex > beforeItem - 1 && rowIndex < item) {
            if (rowIndex == beforeItem) {
              return {
                rowspan: item - beforeItem,
                colspan: 1
              }
            } else {
              return {
                rowspan: 0,
                colspan: 0
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style lang="less">
.financial{
  width: 100%;
  height: calc(100vh - 84px);
  box-sizing: border-box;
  padding: 16px;
  position: relative;
  .el-table--border,
  .el-table--group {
    border-color: rgb(168, 168, 168);
  }
  
  .el-table--border:after,
  .el-table--group:after,
  .el-table:before {
    background-color: rgb(168, 168, 168);
  }
  
  .el-table td,
  .el-table--border th,
  .el-table th.is-leaf {
    border-bottom-color: rgb(168, 168, 168);
  }
  
  .el-table--border td,
  .el-table--border th {
    border-right-color: rgb(168, 168, 168);
  }
  .radioBox{
    position: absolute;
    left: 16px;
    top: 16px;
    width: 600px;
    height: 60px;
    z-index: 99;
  }
  .financialTableBox{
    height: calc(100% - 60px);
    width: 100%;
    overflow: auto;
    .cell{
      position: relative;
      .badgeIconBox{
        position: absolute;
        right: 5px;
        top: 5px;
      }
    }
  }
}

</style>